
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Text;

using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.DataAccess;
using Swaf.DataAccess.AdoNet;

namespace /**Namespace*/Swaf.DataAccess/**Namespace*/
{
	public class /**$ClassName*/DataAccessTemplate/**$ClassName*/ : Swaf.DataAccess.AdoNet.AdoNetDataAccess
	{	/**Formatter*/
		protected {0} m_formatter = new {0}();
		protected override NodeInfo Formatter {{get{{return m_formatter;}}}}
		/**Formatter*/
		public /**$ClassName*/DataAccessTemplate/**$ClassName*/()
		{
		}

		public override object execute(INameAddressSupport info)
		{
			IConnectionItem db = null;
			/**CreateParamsPre*/
			{0} paramType;
			IDbDataParameter p;
			object val;
			/**CreateParamsPre*/
			int retryCount=0;
			int retries = 0;
			string sqql = "";
			/**DbCommandType2*/{0} cmd = null;/**DbCommandType2*/
			while(true)
			{
				try
				{
					/**DbCreate*/
					db = (IConnectionItem)App.appData.get("{0}", info.containsField("_transaction")?info.get("_transaction"):info);
					if(db == null)
						throw new DataRequestException("Unable to retrieve IConnectionItem {0}.", null);

					retryCount=db.retryCount;
					/**DbCreate*/
					/**DbCommandType*/cmd = ((IDbConnection)db.Connection).CreateCommand() as {0};
					cmd.CommandTimeout={1};/**DbCommandType*/
					/**CommandTypeStoredProc*/
					cmd.CommandType = CommandType.StoredProcedure;
					/**CommandTypeStoredProc*//**SqlTrans*/
					cmd.Transaction = ({0})db.ConnectionTrans;
					/**SqlTrans*/
					sqql = createSql(info, cmd);
					cmd.CommandText = sqql;

					/**CreateParam*/
					paramType = ({0})App.factories["{0}"].createFromNickName("{1}");
					p = cmd.Parameters.Add("@{2}", paramType, {3});/**Dir*/
					p.Direction = {0};/**Dir*//**SetVal*/
					val = info.get("{0}", "externalTrusted");
					if(val is IBizObj)
						val = ((IBizObj)val).Xml;
					else if(val is IBizObjList)
						val = ((IBizObjList)val).Xml;
					p.Value = (val == null)?DBNull.Value:val;/**SetVal*/
					/**CreateParam*/

					try
					{
						/**GetResults*/
						IDataReader reader = cmd.ExecuteReader();
						return m_formatter.format(info, reader);
						/**GetResults*//**PutNoResults*/
						return cmd.ExecuteNonQuery();
						/**PutNoResults*/
					}
					catch(Exception dbE)
					{
						if (dbE.Message.StartsWith("General network error"))
						{
							db.release();
							++retries;
							//App.Trace.write(TraceLevels.Normal, "Error executing request {0}. Error was {{0}}", dbE.ToString());
							if (retries > retryCount)
								throw new DataRequestException(this.GetType().Name, "General network error executing data command"+sqql, dbE);
							continue;
						}
						else
							throw new DataRequestException(this.GetType().Name, "Error executing data command" + sqql, dbE);
					}
				}
				catch(Exception ex)
				{
					throw new DataRequestException(this.GetType().Name, "Failure setting up parameters for query: "+sqql, ex);
				}
                finally
                {
                    db.release();
                    cmd.Dispose();
                }
			}
		}

		/**AddParam*/
		protected void addParameter({0} cmd, string name, string dbName, string paramTypeStr, INameAddressSupport info)
		{{
				{1} paramType = ({1})App.factories["{1}"].createFromNickName(paramTypeStr);
				IDbDataParameter p = cmd.Parameters.Add("@" + dbName, paramType);
				object val = info.get(name, "externalTrusted");
				if(val is IBizObj)
					val = ((IBizObj)val).Xml;
				else if(val is IBizObjList)
					val = ((IBizObjList)val).Xml;
				p.Value = (val == null)?DBNull.Value:val;
		}}
		/**AddParam*/

		protected string createSql(INameAddressSupport info, /**CreateSqlParam*/IDbCommand/**CreateSqlParam*/ cmd)
		{
			StringBuilder sql = new StringBuilder(512);
            IBizObj criteria = null;            
            if(info.containsField("criteria"))
			    criteria = info.get("criteria") as IBizObj;

			/**CreateSqlMainBody*/
			/**CreateSqlMainBody*/

			return App.resMgr.resolve(sql.ToString(),new Swaf.Container.NameAddressSupportDictionaryWrapper(info));
		}

	/**FormatterClass*/
	/**FormatterClass*/
	}
}
